package com.hxzy.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxzy.common.exception.HxdsException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author wy
 * @Description 微信工具类 （获取openid）
 * @Date 2023/12/13 17:02
 * @Version 1.0
 */

@Component
public class WeiXinAppUtil {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;


    //https://api.weixin.qq.com/sns/jscode2session?appid=wxdbe6faab1d5c0cd6&secret=ddd1e16808f0381fb9cee1e2da47b9ad&js_code=0e3WQ9100NpIbR1WC1400muz7e1WQ91F&grant_type=authorization_code

    /**
     * 根据微信小程序的授权码换令牌
     * https://api.weixin.qq.com/sns/jscode2session?appid=自己的id&secret=自己的密码&js_code=临时授权码&grant_type=authorization_code*
     * @param code
     * @return
     */
    public String getOpenId(String code) throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        //构建post数据
        MultiValueMap<String, Object> postData = new LinkedMultiValueMap<>();
        postData.add("appid", appId);
        postData.add("secret", appSecret);
        postData.add("js_code", code);
        postData.add("grant_type", "authorization_code");

        //向微信服务器发送post请求
        RestTemplate  restTemplate=new RestTemplate();

        String resultString = restTemplate.postForObject(url, postData, String.class);
       //序列化
        ObjectMapper  objectMapper=new ObjectMapper();
        Map resultMap  = objectMapper.readValue(resultString, Map.class);

        // post请求，返回的结果：
        //  {"session_key":"eL1IRMgf4E4LndpzlvueFA==","openid":"ob61W5xhEqE-eipazDy1B1ZCM7mU"}
        Object openId = resultMap.get("openid");
        if (openId == null || openId.toString().length() == 0) {
            throw new HxdsException("临时登陆凭证错误");
        }
        return openId.toString();
    }

    /**
     * https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的id&secret=你的密钥
     * 获取微信授权码，默认7200秒过期，微信每天只允许2000次/天
     * {"access_token":"75_VCM5zcMjjMnmT9-PdYe46tlk5VH9XGdFSbySRxjDM7towHQaSFzzr8I2Poh8SWp0U31E21-1boS7ylTC4d9bbqwRNRD_N5VJKpNtWPNEnMVAtpVrDftr-KCxysYEAChADAUQS","expires_in":7200}
     * {"errcode":40013,"errmsg":"invalid appid rid: 65797892-2750ee8c-085a0004"}*
     * @return
     */
    public WxAccessToken getAccessToken() throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/cgi-bin/token";

        //构建post数据
        MultiValueMap<String, Object> postData = new LinkedMultiValueMap<>();
        postData.add("appid", appId);
        postData.add("secret", appSecret);
        postData.add("grant_type", "client_credential");

        //向微信服务器发送post请求
        RestTemplate  restTemplate=new RestTemplate();

        String resultString = restTemplate.postForObject(url, postData, String.class);

        ObjectMapper  objectMapper=new ObjectMapper();
        WxAccessToken wxAccessToken  = objectMapper.readValue(resultString, WxAccessToken.class);

        if (Objects.nonNull(wxAccessToken.getAccess_token())) {
            return wxAccessToken;
        } else {
            throw new HxdsException( wxAccessToken.getErrmsg());
        }
    }

}
